package test.chat.client.websockets;

import test.chat.client.view.ChatView;
import test.chat.common.command.Command;
import test.chat.common.command.LoginResponseCommand;
import test.chat.common.command.MessageCommand;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootLayoutPanel;

public class ChatCommandHandler implements ClientCommandHandler {
    private ChatView chatView;

    public ChatCommandHandler(ChatView chatView) {
        this.chatView = chatView;
    }

    @Override
    public void onUnexpectedDisconnect() {
        Window.alert("WebSockets problem");
    }

    @Override
    public void onCommand(Command command) {
        if (command instanceof LoginResponseCommand) {
            LoginResponseCommand c = (LoginResponseCommand) command;

            if (c.getErrorMessage() != null) {
                Window.alert(c.getErrorMessage());
            } else {
                RootLayoutPanel.get().remove(0);

                RootLayoutPanel.get().add(chatView);
            }
        }

        if (command instanceof MessageCommand) {
            chatView.addMessage((MessageCommand)command);
        }
    }
}
